﻿using System;
using System.IO;
using JulMar.Silverlight.Interfaces;
using JulMar.Silverlight.Mvvm;
using MediaBrowserSL.RIA.MediaBrowserServiceReference;
using MediaBrowserSL.RIA.MvvmUtils;
using MediaBrowserSL.RIA.Services;
using MediaBrowserSL.RIA.Tools;
using System.Windows;
using Jade.Tools.SL.Windows.Extensions;
using MediaBrowserSL.RIA.MvvmUtils.UI;
using System.ServiceModel;

namespace MediaBrowserSL.RIA.ViewModels
{
    /// <summary>
    /// Manage Book View Model
    /// </summary>
    public class ManageBooksViewModel : ViewModelBase
    {
        #region Private Member

        private IMediaRiaServices service;
        private Media newMedia;
        private FileInfo selectedFileBook;
        private IErrorVisualizer errorVisualizer;
        private ICustomMessageBoxVisualizer customMessageBoxVisualizer;
        private bool isSaving;
        private bool isAddingBook;

        #endregion

        #region Public Member

        public Media NewMedia
        {
            get
            {
                return newMedia;
            }
            set
            {

                newMedia = value;
                OnPropertyChanged("NewMedia");
            }
        }

        public FileInfo SelectedFileBook
        {
            get { return selectedFileBook; }
            set
            {
                selectedFileBook = value;
                OnPropertyChanged("SelectedFileBook");
                NewMedia.UrlContent = selectedFileBook.ToString();
            }
        }

        public bool IsAddingBook
        {
            get { return isAddingBook; }
            set
            {
                isAddingBook = value;
                OnPropertyChanged("IsAddingBook");
            }
        }


        public bool IsSaving
        {
            get
            {
                return isSaving;
            }
            set
            {

                isSaving = value;
                OnPropertyChanged("IsSaving");
                RaiseCanExecuteChanged();
            }
        }

        #endregion

        #region Command

        public DelegatingCommand SaveBookCommand
        {
            get;
            private set;
        }

        #endregion

        #region Ctor

        public ManageBooksViewModel(IMediaRiaServices service)
        {
            this.service = service;

            SaveBookCommand = new DelegatingCommand(SaveBook, CanSaveBook);

            errorVisualizer = Resolve<IErrorVisualizer>();
            customMessageBoxVisualizer = Resolve<ICustomMessageBoxVisualizer>();

            //Init Mediator
            RegisterWithMessageMediator();
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Save Book and Upload File
        /// </summary>
        private void SaveBook()
        {
            IsSaving = true;
            //Create Media
            if (NewMedia.Id == 0)
            {
                NewMedia.CreationDate = DateTime.Now;
                service.CreateMedia(OnBookCreated, NewMedia, SessionMb.CurrentUser, null, selectedFileBook);
            }
            //Update Media
            else
            {
                service.UpdateMedia(OnBookUpdated, NewMedia);
            }
        }

        /// <summary>
        /// On Book Created
        /// </summary>
        /// <param name="Media"></param>
        /// <param name="ex"></param>
        private void OnBookCreated(Media m, Exception ex)
        {
            IsSaving = false;
            if (ex == null)
            {
                SendMessage(MediatorMessages.AddBookToList, m);
                CloseCommand.Execute(null);
            }
            else if (ex.GetType().Equals(typeof(FullServerException)))
            {
                if (customMessageBoxVisualizer != null)
                {
                    customMessageBoxVisualizer.Show(null,
                                                        "Votre espace serveur est plein !",
                                                        "Espace indisponible",
                                                        MessageBoxButton.OK,
                                                        MessageBoxImage.Error);
                }

            }
            else
            {
                if (customMessageBoxVisualizer != null)
                {
                    customMessageBoxVisualizer.Show(null, ((FaultException<ErrorDataContract>)ex).Detail.Detail, ex.Message, MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        /// <summary>
        /// On Book Updated
        /// </summary>
        /// <param name="ex"></param>
        private void OnBookUpdated(Exception ex)
        {
            IsSaving = false;
            if (ex == null)
            {
                SendMessage(MediatorMessages.UpdateBookToList, NewMedia);
                CloseCommand.Execute(null);
            }
            else
            {
                if (customMessageBoxVisualizer != null)
                {
                    customMessageBoxVisualizer.Show(null, ((FaultException<ErrorDataContract>)ex).Detail.Detail, ex.Message, MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        /// <summary>
        /// Can Save Album
        /// </summary>
        /// <returns></returns>
        private bool CanSaveBook()
        {
            bool result = false;

            if (!IsSaving)
            {
                result = NewMedia.ValidData() && !String.IsNullOrEmpty(NewMedia.UrlContent);
            }

            return result;
        }

        /// <summary>
        /// New Media Property Changed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void NewMedia_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            RaiseCanExecuteChanged();
        }

        /// <summary>
        /// Raise can execute
        /// </summary>
        private void RaiseCanExecuteChanged()
        {
            SaveBookCommand.RaiseCanExecuteChanged();
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Edit Album
        /// </summary>
        [MessageMediatorTarget(MediatorMessages.EditBook)]
        public void EditBook(Media media)
        {
            NewMedia = media.Clone();
            NewMedia.Category = new Category() { Id = 4 };
            NewMedia.UrlContent = Path.GetFileName(media.UrlContent);

            IsAddingBook = (NewMedia.Id == 0) ? true : false;

            NewMedia.PropertyChanged += NewMedia_PropertyChanged;
        }

        #endregion
    }
}
